#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

#include "ft_timers.h"

//init the timer data
void set_ft_timer(struct ft_timer_t* timer, unsigned long timeout)
{
  //system call for exact time
  gettimeofday(&timer->start,NULL);
  timer->timeout.tv_sec = timer->start.tv_sec + (timeout/1000000L);
  timer->timeout.tv_usec = timer->start.tv_usec + (timeout % 1000000L);
  //random heuristic for sleeping time
  timer->sleep_time = (timeout >> 8)?(timeout >> 8):250L;
}

//do the sleep - deprecated - i'm using poll now
void ft_timer_sleep(struct ft_timer_t* timer)
{
  struct timeval tmp_t;
  gettimeofday(&tmp_t,NULL);
  if (tmp_t.tv_usec < timer->timeout.tv_usec && 
      tmp_t.tv_sec < timer->timeout.tv_sec)
    usleep(timer->sleep_time);
}

//check the timers values, returns negative if we have
int check_ft_timer(struct ft_timer_t* timer)
{
  struct timeval tmp_t;
  gettimeofday(&tmp_t,NULL);
  return 1000000*(timer->timeout.tv_sec - tmp_t.tv_sec) + (timer->timeout.tv_usec - tmp_t.tv_usec);
}

//returns the time of a certain timer, used for rtt calculations
unsigned long delta_ft_timer(struct ft_timer_t* timer)
{
  struct timeval tmp_t;
  gettimeofday(&tmp_t,NULL);
  return (tmp_t.tv_usec - timer->start.tv_usec) + 1000000*(tmp_t.tv_sec - timer->start.tv_sec);
}
